package com.piz.service.productservice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.piz.dao.product.ProductClassificationDao;
import com.piz.dao.product.ProductDao;
import com.piz.model.ItemClassification;
import com.piz.model.ItemDetails;
import com.piz.model.ItemPricing;
import com.piz.service.common.UnexpectedServiceException;
import com.piz.service.model.ItemBean;


/**
 * @author Administrator
 *
 */
@Component("productMgmtService")
public class ProductMgmtService {
	
	@Autowired
	ProductDao productDao;
	
	@Autowired
	ProductClassificationDao classificationDao;
	
	@Autowired
	ProductService productService;
	/**
	 * @return List<ItemDetails> with criteria on category, class, taste
	 */
	public List<ItemDetails> fetchItemByCriteria(Long classId, Long catId, Long tasteId) {
		
		List<ItemDetails> items;
		try {
				items = productDao.fetchProductsByCriteria(classId, catId, tasteId);
		} catch (Exception e) {
			throw new UnexpectedServiceException("Error in fetching items with criteria");
		}
		
		return items;
	}
	
	public List<ItemBean> populateItemBean(List<ItemDetails> items)
	{
		List<ItemBean> itemBeans =  new ArrayList<ItemBean>();
		Map<Integer, String> typeMap = productService.fetchProductTypeMap();
		Map<Integer, String> catMap = productService.fetchProductCategoryMap();
		Map<Integer, String> tasteMap = productService.fetchPizzaTasteMap();
		String editAction = "addProduct.action?id=";
		String deleteAction = "deleteProduct.action?id=";
		String priceString = "";
		
		for(ItemDetails item : items)
		{
			for(ItemPricing price : item.getPrices())
			{
				priceString = priceString + price.getPrice().toString() + " ";
			}
			ItemBean itemBean = new ItemBean(item.getId(), item.getName(), item.getDescription(),
					item.getImage(), typeMap.get(item.getCategoryId().intValue()), catMap.get(item.getClassificationId().intValue()),
					tasteMap.get(item.getTasteId().intValue()), priceString, editAction + item.getId().toString(),
					deleteAction + item.getId().toString(), (item.getCreatedAt() == null)? "":item.getCreatedAt().toString());
			
			itemBeans.add(itemBean);
			priceString = "";
		}
		
		return itemBeans;
	}
	
	public void deleteProduct(Long id)
	{
		try {
			productDao.deleteProduct(id);
		} catch (Exception e) {
			throw new UnexpectedServiceException("error product delete service.");
		}
		
	}
	
	public void addProductClass(ItemClassification itemClass)
	{
		try {
			String fileName = "";
			 try {
				 if(itemClass.getFile() != null)
					 fileName = "images1/"+itemClass.getName()+"/"+itemClass.getName();
			} catch (Exception e) {
				throw new UnexpectedServiceException("Exception in creating file path "+fileName, e);
			}
			itemClass.setCreatedAt(new Date());
			itemClass.setImage(fileName);
			classificationDao.addProductClass(itemClass);
		} catch (Exception e) {
			throw new UnexpectedServiceException("error product delete service.");
		}
		
	}
	
	public void deleteProductClass(Long id)
	{
		try {
			classificationDao.deleteProductClass(id);
		} catch (Exception e) {
			throw new UnexpectedServiceException("error product delete service.");
		}
		
	}
	
	public ItemClassification fetchProductClassById(Long id)
	{
		ItemClassification cls;
		try {
			cls = classificationDao.fetchClassById(id);
			return cls;
		} catch (Exception e) {
			throw new UnexpectedServiceException("error product delete service.");
		}
	}
	
	public void saveProductClassImage(String realPath,ItemClassification cat) 
	{

		MultipartFile multipartFile = cat.getFile();
		 String fileName="";
		// image type of file processing...
		 System.err.println("-------------------------------------------");
		 try {
		   InputStream inputStream = null;
		   OutputStream outputStream = null;
		   if (multipartFile.getSize() > 0) {
			  inputStream = multipartFile.getInputStream();
			  fileName = realPath + "/images1/"+cat.getName();
			  File theDir = new File(fileName);
			  if (!theDir.exists())
			  {
			    System.out.println("creating directory: " + fileName);
			    boolean result = theDir.mkdirs();  
			    if(result){    
			       System.out.println("DIR created");  
			     }

			  }
			  fileName = fileName+"/"+cat.getName();
			  outputStream = new FileOutputStream(fileName);
			  int readBytes = 0;
			  byte[] buffer = new byte[10000];
			  while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
				 outputStream.write(buffer, 0, readBytes);
			   }
			  outputStream.close();
			  inputStream.close();
			}	    
		  } catch (Exception e) {
			 throw new UnexpectedServiceException("Exception in saving image file: "+fileName,e);
		  }
		 // .......................................... 
	
	}
}
